<?php

namespace backend\modules\business\controllers;

use backend\controllers\AdminController;
use common\components\Upload;
use Yii;
use common\models\business\BusinessInspection;
use backend\modules\business\models\BusinessInspectionSearch;
use yii\db\Query;
use yii\helpers\Url;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * InspectionController implements the CRUD actions for BusinessInspection model.
 */
class InspectionController extends AdminController
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all BusinessInspection models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new BusinessInspectionSearch();
        $search = Yii::$app->request->queryParams;
        $search['BusinessInspectionSearch']['is_del'] = BusinessInspection::ISDEL_NODEL;
        $dataProvider = $searchModel->search($search);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }



    /**
     * 回收站
     */
    public function actionRecycle()
    {
        $searchModel = new BusinessInspectionSearch();
        $search = Yii::$app->request->queryParams;
        $search['BusinessInspectionSearch']['is_del'] = BusinessInspection::ISDEL_DEL;
        $dataProvider = $searchModel->search($search);

        return $this->render('recycle', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }


    /**
     * @param $id
     * @return string
     * 从回收站恢复
     */
    public function actionRecycleBack($id)
    {
        $res = Yii::$app->db->createCommand()->update(BusinessInspection::tableName(),['is_del'=>BusinessInspection::ISDEL_NODEL],'id=:id',[':id'=>$id])
            ->execute();

        return $res?$this->dialog('操作成功','success',Url::to(['index'])):$this->dialog('操作失败');
    }

    /**
     * Displays a single BusinessInspection model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new BusinessInspection model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new BusinessInspection();

        if ($model->load(Yii::$app->request->post())){
            if(false !== $photo = Upload::upload($model,'pigpen_photo')){
                $model->setAttribute('pigpen_photo',$photo);
            }
            if(false !== $photo = Upload::upload($model,'feed_photo')){
                $model->setAttribute('feed_photo',$photo);
            }
            if(false !== $photo = Upload::upload($model,'pigphoto')){
                $model->setAttribute('pigphoto',$photo);
            }
            if($model->save()){
                return $this->redirect(['view', 'id' => $model->id]);
            }else{
                return $this->dialog($this->checkError($model));
            }
        }else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing BusinessInspection model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);


        if ($model->load(Yii::$app->request->post())){
            $model->setScenario('update');
            if(false !== $iphoto = Upload::upload($model,'pigpen_photo')){
                $model->setAttribute('pigpen_photo',$iphoto);
            }
            if(false !== $sphoto = Upload::upload($model,'feed_photo')){
                $model->setAttribute('feed_photo',$sphoto);
            }
            if(false !== $photo = Upload::upload($model,'pigphoto')){
                $model->setAttribute('pigphoto',$photo);
            }
            if($model->save()){
                //返回列表页
                return "<script>history.go(-2)</script>";
//                return $this->redirect(['view', 'id' => $model->id]);
            }else{
                return $this->dialog($this->checkError($model));
            }
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing BusinessInspection model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        Yii::$app->db->createCommand()->update(BusinessInspection::tableName(),['is_del'=>BusinessInspection::ISDEL_DEL],'id=:id',[':id'=>$id])
            ->execute();
//        $this->findModel($id)->delete();
        return $this->redirect(['index']);
    }



    //批量设置审核
    public function actionSetpass()
    {
        $ids = Yii::$app->request->post('ids');
        if(!empty($ids)){
            $idstr = implode(',',$ids);
            Yii::$app->db->createCommand('update '.BusinessInspection::tableName().' set status=:status where id in('.$idstr.')')
                ->bindValues([':status'=>BusinessInspection::STATUS_PASSED])
                ->execute();
            return \GuzzleHttp\json_encode(['msg'=>'操作成功','status'=>0]);
        }

        return \GuzzleHttp\json_encode(['msg'=>'请选择对应的仔猪','status'=>1]);


    }


    /**
     * @return string
     * 批量删除巡检记录
     */
    public function actionMutiDelete()
    {
        $ids = Yii::$app->request->post('ids');
        if(!empty($ids)){
            $idstr = implode(',',$ids);
            Yii::$app->db->createCommand('update '.BusinessInspection::tableName().' set is_del=:is_del where id in('.$idstr.')')
                ->bindValues([':is_del'=>BusinessInspection::ISDEL_DEL])
                ->execute();
            return \GuzzleHttp\json_encode(['msg'=>'操作成功','status'=>0]);
        }

        return \GuzzleHttp\json_encode(['msg'=>'请选择对应的仔猪','status'=>1]);

    }

    /**
     * Finds the BusinessInspection model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return BusinessInspection the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = BusinessInspection::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }







}
